﻿using DYH.Extensions.CAD.Tools.Cad;

namespace DYH.Extensions.CAD.Tools;

/// <summary>
/// Linq扩展工具
/// </summary>
public static class LinqTool
{
    /// <summary>
    /// 分组
    /// </summary>
    /// <param name="list">要分组的列表</param>
    /// <param name="func">分组条件</param>
    /// <typeparam name="T">类型</typeparam>
    /// <returns>分组结果</returns>
    public static List<List<T>> Friends<T>(this IEnumerable<T> list, Func<T, T, bool> func)
    {
        // 存放结果的列表
        List<List<T>> result = [];
        // 条件列表复制一份，因为算法会移除元素，避免移除原表
        var tList = list.ToList();
        using var pmm = ProgressMeterManager.Start("正在分组", tList.Count);
        while (tList.Count > 0)
        {
            var queue = new Queue<T>();
            var first = tList.First();
            tList.RemoveAt(0);
            queue.Enqueue(first);
            List<T> findList = [];
            while (queue.Count > 0)
            {
                pmm.Step();
                var x1 = queue.Dequeue();
                findList.Add(x1);
                for (var i = tList.Count - 1; i >= 0; i--)
                {
                    var x2 = tList[i];
                    if (func(x1, x2))
                    {
                        queue.Enqueue(x2);
                        tList.RemoveAt(i);
                    }
                }
            }

            result.Add(findList);
        }

        return result;
    }
}